package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"short-drama-mgr/cache"
	"short-drama-mgr/models"
	"short-drama-mgr/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.Users
	redis_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*3)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次，封禁3小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var drama []models.Drama
	redis_key := "list_page+" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		models.DB.Offset(offset).Limit(size).Find(&drama)
		jsonData, _ := json.Marshal(drama)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &drama)
	}
	var count int64
	models.DB.Model(&models.Drama{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  400,
		"msg":   "查询成功",
		"data":  drama,
		"count": count,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var drama models.Drama
	redis_key := "detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		models.DB.Where("id=?", id).Debug().Find(&drama)
		jsonData, _ := json.Marshal(drama)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &drama)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": drama,
	})
	return
}
